use std::{env, error::Error, fs};

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.file_path)?;

    let results = if config.ignore_case {
        // println!("search_case_insensitive, params[query = {}]\n", &config.query);
        search_case_insensitive(&config.query, &contents)
    } else {
        // println!("search, params[query = {}]\n", &config.query);
        search(&config.query, &contents)
    };

    for line in results {
        println!("{line}");
    }

    Ok(())
}

pub struct Config {
    pub query: String,
    pub file_path: String,
    pub ignore_case: bool,
}

impl Config {

    pub fn build(args: impl Iterator<Item = String>) -> Result<Config, &'static str> {

        let mut plain_args: Vec<String> = Vec::new();
        let mut double_line_args: Vec<String> = Vec::new();

        for arg in args {
            if arg.starts_with("--") {
                double_line_args.push(arg);
            } else {
                plain_args.push(arg);
            }
        }

        if plain_args.len() < 3 {
            return Err("not enough arguments");
        }
        
        let query = plain_args[1].to_string();
        let file_path = plain_args[2].to_string();
        
        let ignore_case = match env::var("IGNORE_CASE") {
            Ok(var) => var != "0",
            Err(_) => double_line_args.contains(&"--ignore-case".to_string()),
        };

        Ok(Config { query, file_path, ignore_case })
    }
}

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let mut results = Vec::new();
    for line in contents.lines() {
        if line.contains(query) {
            results.push(line);
        }
    }
    results
}

pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let mut results = Vec::new();
    let query = query.to_lowercase();
    for line in contents.lines() {
        if line.to_lowercase().contains(&query) {
            results.push(line);
        }
    }
    results
}





#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn one_result() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.";

        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
    }

    #[test]
    fn case_sensitive() {
        let query = "duct";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";

        assert_eq!(vec!["safe, fast, productive."], search(query, contents));
    }

    #[test]
    fn case_insensitive() {
        let query = "rUsT";
        let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";

        assert_eq!(
            vec!["Rust:", "Trust me."],
            search_case_insensitive(query, contents)
        );
    }
}